#!/usr/bin/python3
# -*- coding: utf-8; tab-width: 4; indent-tabs-mode: t -*-

import os
import sys
import pwd
sys.path.append('/usr/lib64/fpemud-os-sysman')
from fm_param import FmConst


class Arguments:

    def __init__(self):
        self.pid = int(sys.argv[1])
        self.uid = int(sys.argv[2])
        self.gid = int(sys.argv[3])
        self.signal = sys.argv[4]
        self.timestamp = sys.argv[5]
        self.hostname = sys.argv[6]
        self.executable = sys.argv[7]


def isCoreDumpEnabledForUser(pwEntry):
    cfgDir = os.path.join(pwEntry.pw_dir, FmConst.userUsrmanCfgDir)
    coreDumpEnableFile = os.path.join(cfgDir, "enable-coredump")
    return os.path.exists(coreDumpEnableFile)


def saveCoreDumpFile(args, pwEntry):
    cacheDir = os.path.join(pwEntry.pw_dir, FmConst.userUsrmanCacheDir)
    coreDumpFile = os.path.join(cacheDir, "core.dump")
    os.makedirs(cacheDir, exist_ok=True)
    with open(coreDumpFile, "wb") as f:
        while True:
            data = sys.stdin.buffer.read(1024)
            if not data:
                break
            f.write(data)
    os.chown(coreDumpFile, args.uid, args.gid)


if __name__ == "__main__":
    args = Arguments()
    pwEntry = pwd.getpwuid(args.uid)
    if isCoreDumpEnabledForUser(pwEntry):
        saveCoreDumpFile(args, pwEntry)
